<template>
  <PrivacyPopup></PrivacyPopup>
  <TrackButton :track-id="settingId" :type="TrackType.ApplianceDetail" :button-id="settingButtonId">
    <PageLayout full :pageStyle="pageStyle" class="applianceSettings-view">
      <template #header>
        <HeaderLayout show-back auto-back :header-style="headerStyle">
          <view>{{ $t('ApplianceSettings.Navigate.Title') }}</view>
        </HeaderLayout>
      </template>
      <view class="appliance-settings">
        <SettingGroup title=" ">
          <!-- 家电信息 -->
          <SettingRow
            alignment="center"
            has-arrow
            :extra="$t('ApplianceSettings.UseGuide.Lable')"
            @click="gotoUseGuide"
          >
            <template #label>
              <view class="appliance-info-label">
                <alt-picture class="appliance-image" :src="applianceImg" />
                <view v-if="guest" class="share-icon">{{ $t('ApplianceSettings.Share.Lable') }}</view>
              </view>
            </template>
          </SettingRow>

          <!-- 耗材服务 -->
          <SettingRow
            v-if="consumablesServiceVisible"
            has-arrow
            :label="$t('ApplianceSettings.ConsumablesService.Lable')"
            :extra="$t('ApplianceSettings.ConsumablesService.Check.Text')"
            @click="jumpConsumablesService"
          />
        </SettingGroup>

        <!-- 家电设置 -->
        <SettingGroup :title="$t('ApplianceSettings.Group.ApplianceSet.Lable')">
          <SettingRow
            has-arrow
            :label="$t('ApplianceSettings.ApplianceName.Lable')"
            :value="name"
            @click="showRenameModal('appliance')"
          />
          <SettingRow
            v-if="!guest && type != 'HVN'"
            has-arrow
            :label="$t('ApplianceSettings.ShareManage.Lable')"
            @click="gotoShare"
          />
          <SettingRow
            v-if="connected && type === 'TT'"
            has-arrow
            :label="$t('ApplianceSettings.RunModel.Lable')"
            :value="summerMode ? $t('ApplianceSettings.SummerMode.Text') : $t('ApplianceSettings.WinterMode.Text')"
            @click="jumpStringSetting('运行模式', summerModeKey, summerMode ? 1 : 0)"
            @label-click="runModeVisible = true"
          >
            <template #label-suffix>
              <image class="tips-icon" src="@/pages/appliance/static/TT/ic_setting_runningmode.png"></image>
            </template>
          </SettingRow>

          <!-- 参数设置 -->
          <!-- 嵌饮机 参数设置 -->
          <block v-if="type === 'BIWD'">
            <SettingRow
              v-if="sleepTimeVisible"
              has-arrow
              :label="$t('ApplianceSettings.StandbyTime.Lable')"
              :value="sleepTime"
              :plain-disabled="!connected"
              @click="jumpStringSetting('屏幕休眠时间', StandbyTime, sleepTimeValue)"
            />
            <SettingRow
              v-if="nightModeStateVisible"
              :has-arrow="!connected"
              :label="$t('ApplianceSettings.NightModeState.Lable')"
              :plain-disabled="!connected"
              @click="changeNightModeState"
            >
              <template #extra>
                <switch
                  v-if="connected"
                  :color="switchColor"
                  :checked="nightModeState"
                  :disabled="!connected"
                  @click="settingId = 'ApplianceSettings.NightModeState.Lable'"
                />
              </template>
            </SettingRow>
            <SettingRow
              v-if="NightModeTimeVisible"
              has-arrow
              :label="$t('ApplianceSettings.ActivationTime.Lable')"
              :value="connected ? activationTime : ''"
              :disabled="!nightModeState && connected"
              :plain-disabled="!connected"
              @click="changeActivationTime"
            />
            <SettingRow
              v-if="nightModeBrightVisible"
              has-arrow
              :label="$t('ApplianceSettings.NightModeBright.Lable')"
              :value="connected ? nightModeBright : ''"
              :disabled="!nightModeState && connected"
              :plain-disabled="!connected"
              @click="jumpStringSetting('屏幕亮度', NightModeBright, nightModeBright - 1)"
            />
            <!-- 童锁设置 -->
            <SettingRow
              v-if="lockBIWDSetVisible"
              label="童锁设置"
              desc="适用于60°以上童锁是否打开的设置"
              :has-arrow="!connected"
              :plain-disabled="!connected"
              @click="changeLockBIWDSet"
            >
              <template #extra>
                <switch
                  v-if="connected"
                  :color="switchColor"
                  :checked="lockBIWDSet"
                  :disabled="!connected"
                  @change="changeLockBIWDSet"
                  @click="settingId = '童锁设置'"
                />
              </template>
            </SettingRow>
            <!-- 冰水开关 -->
            <SettingRow
              v-if="coolWaterSetVisible"
              label="冰水设置"
              :has-arrow="!connected"
              :plain-disabled="!connected"
              @click="changeCoolWaterSet"
            >
              <template #extra>
                <switch
                  v-if="connected"
                  :color="switchColor"
                  :checked="coolWaterSet"
                  :disabled="!connected"
                  @change="changeCoolWaterSet"
                  @click="settingId = '冰水设置'"
                />
              </template>
            </SettingRow>
            <!-- 设置冰水温度 -->
            <SettingRow
              v-if="coolWaterTempVisible"
              label="冰水温度"
              has-arrow
              :value="connected ? coolWaterTemp + '℃' : ''"
              :disabled="!coolWaterSet && connected"
              :plain-disabled="!connected"
              @click="jumpStringSetting('冰水温度', BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE, coolWaterTemp)"
            />
          </block>
          <!-- 美妆冰箱 参数设置 -->
          <block v-else-if="type === 'RefrigeratorB'"></block>
          <!-- 非嵌饮机 参数设置 -->
          <block v-else="type !== 'BIWD'">
            <SettingGroup
              v-for="(group, groupIndex) in settingList"
              :key="groupIndex"
              :title="group.settingsGroup !== 'SettingsGroup.TopSettings' ? group.settingsGroupName : ''"
            >
              <block v-for="(setting, settingIndex) in group.settings" :key="setting.key">
                <!-- 开关 -->
                <SettingRow
                  v-if="typeof setting.value === 'boolean'"
                  :label="setting.name"
                  :desc="setting.mediumDescription"
                  :disabled="!remoteControl"
                  :plain-disabled="!connected"
                  @click="getSettingId(setting)"
                  @tap.stop
                >
                  <template #extra>
                    <switch
                      :color="switchColor"
                      :disabled="!connected"
                      :checked="setting.checked"
                      @change="changeChecked(groupIndex, settingIndex, setting)"
                    />
                  </template>
                </SettingRow>
                <!-- 设置日期和时间 -->
                <SettingRow
                  v-else-if="setting.key === SETTING_APPLIANCEDATETIME"
                  :label="setting.name"
                  :value="autoTime"
                  :disabled="!remoteControl"
                  :plain-disabled="!connected"
                  :has-arrow="!autoTimeFlag"
                  @click="openSetDateTime(setting)"
                />
                <!-- 机器时间 -->
                <SettingRow
                  v-else-if="setting.key === MACHINE_TIME"
                  :label="setting.name"
                  :value="applianceTime"
                  :disabled="!remoteControl"
                  :plain-disabled="!connected"
                  :has-arrow="remoteControl && connected"
                  @click="openApplianceTime(setting)"
                />
                <!-- 时间格式的设置项 -->
                <SettingRow
                  v-else-if="shouldUseTimePicker(setting)"
                  :label="setting.name"
                  :desc="setting.mediumDescription"
                  :value="getTimeDisplayValue(setting)"
                  :disabled="!remoteControl"
                  :plain-disabled="!connected"
                  :has-arrow="remoteControl && connected"
                  @click="openTimePicker(setting)"
                />
                <!-- 跳转设置 -->
                <SettingRow
                  v-else
                  has-arrow
                  :label="setting.name"
                  :desc="setting.key !== SETTING_REMOTE_CONTROL_LEVEL ? setting.mediumDescription : ''"
                  :disabled="!remoteControl && setting.key !== SETTING_REMOTE_CONTROL_LEVEL"
                  :plain-disabled="!connected"
                  @click="jumpParamsSetting(setting)"
                >
                  <template #value>
                    <text v-if="setting.displayvalue">{{ setting.displayvalue }}</text>
                    <text v-else-if="typeof setting.value === 'number' || setting.value">{{ setting.value }}</text>

                    <text v-if="setting.unit">{{ setting.unit }}</text>
                  </template>
                </SettingRow>
              </block>
            </SettingGroup>
          </block>
        </SettingGroup>

        <!--参数设置-->
        <SettingGroup v-if="type === 'HVN'" :title="$t('ApplianceSettings.Group.ParamsSet.Lable')">
          <SettingRow :label="$t('ApplianceSettings.DisturbMode.Lable')" :plain-disabled="!connected">
            <template #extra>
              <switch
                v-if="connected"
                :color="switchColor"
                :checked="hvnNightModeState"
                :disabled="!connected"
                @change="changeNightModeState"
                @click="settingId = 'ApplianceSettings.DisturbMode.Lable'"
              />
              <image class="alt-icon" src="@/static/ic_right_arrow.png" mode="aspectFit"></image>
            </template>
          </SettingRow>
          <SettingRow
            :label="$t('ApplianceSettings.ActivationTime.Lable')"
            has-arrow
            :value="activationTime"
            :disabled="!hvnNightModeState"
            @click="changeActivationTime"
          />
        </SettingGroup>

        <template v-if="type === 'TT' && connected">
          <!--参数设置-->
          <SettingGroup :title="$t('ApplianceSettings.Group.ParamsSet.Lable')">
            <SettingRow
              :label="$t('ApplianceSettings.AlgorithmSwitch.Lable')"
              @click="settingId = 'ApplianceSettings.AlgorithmSwitch.Lable'"
            >
              <template #extra>
                <switch-control :checked="algorithmSwitch" @change="changeAlgorithm" />
                <!-- <switch :color="switchColor" :checked="algorithmSwitch" @change="changeAlgorithm" /> -->
              </template>
            </SettingRow>
          </SettingGroup>
          <!--设备状态-->
          <SettingGroup :title="$t('ApplianceSettings.Group.DeviceSatatus.Lable')">
            <SettingRow
              v-if="!boilerErr"
              :label="$t('ApplianceSettings.FrozenStatus.Lable')"
              :value="
                frozenStatus
                  ? $t('ApplianceSettings.FrozenStatus.Saving.Text')
                  : $t('ApplianceSettings.FrozenStatus.NoOpen.Text')
              "
              @click="settingId = 'ApplianceSettings.FrozenStatus.Lable'"
            />
            <SettingRow
              :label="$t('ApplianceSettings.WaterPressure.Lable')"
              :value="
                waterPressure === 0 ? $t('ApplianceSettings.WaterPressure.InvalidValue.Text') : waterPressure + ' Mpa'
              "
              @label-click="showWaterPressureTips"
              @click="settingId = 'ApplianceSettings.WaterPressure.Lable'"
            >
              <template #label-suffix>
                <image class="tips-icon" src="@/pages/appliance/static/TT/ic_setting_runningmode.png"></image>
              </template>
            </SettingRow>
          </SettingGroup>
          <!--房间管理-->
          <SettingGroup v-if="roomList.length > 0" :title="$t('ApplianceSettings.Group.RoomManage.Lable')">
            <SettingRow
              v-for="(room, index) in roomList"
              :key="index"
              is-button-extra
              :label="room.key == 'Rm0' ? room.name + $t('ApplianceSettings.RoomMain.Text') : room.name"
              :value="$t('ApplianceSettings.UpdateRoom.Text')"
              @click="showRenameModal('room', room.name, index)"
            />
          </SettingGroup>
        </template>

        <!-- commands 重置-->
        <template v-if="appliance">
          <block v-for="(commandGroup, groupIndex) in commandsGroups" :key="groupIndex">
            <SettingGroup v-if="commandGroup.visible" :title="$t(commandGroup.commandName)">
              <SettingRow
                v-for="(command, commandIndex) in commandGroup.commands"
                :key="commandIndex"
                has-arrow
                is-button-extra
                :label="$t(command.name)"
                :desc="command.des"
                :extra="$t(command.btnName)"
                :disabled="!remoteControl || !remoteStart"
                @click="resetCommand(haId, command)"
              />
            </SettingGroup>
          </block>
        </template>

        <!-- 固件升级 HVN不显示固件升级 -->
        <block v-if="type !== 'HVN'">
          <!-- 非TT 固件升级 -->
          <SettingGroup v-if="type !== 'TT'" :title="$t('Appliance.Settings.FirmwareUpgrade.Title')">
            <SettingRow
              has-arrow
              :label="$t('Appliance.Settings.FirmwareUpgrade.Title')"
              :disabled="!connected"
              @click="otaHelper ? otaHelper.toUpgradePage() : toDemoUpgradePage()"
              @tap="FirmwareUpgrade"
            >
              <template #extra>
                <view v-if="otaHelper?.upgradeDetected.value" class="ota-badge">1</view>
              </template>
            </SettingRow>
            <!-- BIWD Value ota测试 -->
            <SettingRow
              v-if="isShowBiwdValueOta"
              has-arrow
              label="ota入口"
              :plain-disabled="!connected"
              @click="jumpBiwdValueOta"
            >
              <template #extra>
                <view v-if="upgradeBiwdNumber !== 0" class="ota-badge">{{ upgradeBiwdNumber }}</view>
              </template>
            </SettingRow>
          </SettingGroup>

          <!-- MR120 固件升级 -->
          <SettingGroup v-else-if="connected && isMR120" :title="$t('Appliance.Settings.FirmwareUpgrade.Title')">
            <SettingRow
              has-arrow
              :label="$t('Appliance.Settings.FirmwareUpgrade.Title')"
              @click="toOtaUpdate"
              @tap="FirmwareUpgrade"
            >
              <template #extra>
                <view v-if="isUpgradeMR120 && upgradeNumber !== 0" class="ota-badge">{{ upgradeNumber }}</view>
              </template>
            </SettingRow>
            <!-- TT ota版本信息 -->
            <SettingRow :label="$t('ApplianceSettings.CurrentVersion.Label')" :value="currentVersionTT" />
            <SettingRow :label="$t('ApplianceSettings.LatestVersion.Label')" :value="latestVersionTT" />
          </SettingGroup>
        </block>

        <!-- 产品信息 -->
        <SettingGroup :title="$t('ApplianceSettings.Group.ProductInfo.Lable')" @tap.stop>
          <SettingRow
            v-if="detail?.enumber"
            :label="$t('ApplianceSettings.ProductInfo.Enumber.Lable')"
            :value="detail?.enumber"
            @click="settingId = 'ApplianceSettings.ProductInfo.Enumber.Label'"
          />
          <SettingRow v-if="haId" :label="$t('ApplianceSettings.ProductInfo.HaId.Lable')" :value="haId" />
          <SettingRow v-if="vib" :label="$t('ApplianceSettings.ProductInfo.Vib.Lable')" :value="vib" />
          <SettingRow v-if="FU_ver.value as number > 0 " :label="FU_ver.name" :value="FU_ver.value" />
          <SettingRow v-if="detail?.fd" :label="$t('ApplianceSettings.ProductInfo.FD.Lable')" :value="detail?.fd" />
          <SettingRow v-if="detail?.zn" :label="$t('ApplianceSettings.ProductInfo.ZN.Lable')" :value="detail?.zn" />
        </SettingGroup>

        <view class="bottom-actions">
          <SettingGroup title=" ">
            <SettingRow @click="removeAppliance">
              <view class="remove-appliance">{{ $t('ApplianceSettings.Buttom.Button') }}</view>
            </SettingRow>
          </SettingGroup>
        </view>

        <ErrorTips v-model:visible="errorTipsFlag" :error-text="errorTipsText"></ErrorTips>
      </view>
    </PageLayout>
  </TrackButton>
  <SmartDryingModal
    v-model:show="smartDrying.modalVisible.value"
    :value="smartDrying.status.value"
    @confirm="smartDrying.onModalConfirm"
  />
  <!-- 共享提示 -->
  <VirtualShareNotice v-model:show="virtualShareNotice.show.value" />
  <Modal
    :visible="showRemoveDialog"
    :title="$t('APP.Common.Tips.Text')"
    :description="removeText"
    :cancel-text="$t('APP.Common.Cancel.Text')"
    :ok-text="$t('APP.Common.Confirm.Text')"
    @ok="confirmRemove"
    @cancel="cancelRemove"
  />
  <!-- 修改家电名称弹框 -->
  <RenameModal
    ref="RenameModalRef"
    v-model:show="renameModalVisible"
    :title="renameTitle"
    :ok-text="$t('ApplianceSettings.RenameModal.Ok.Button')"
    :cancel-text="$t('ApplianceSettings.RenameModal.Cacnle.Button')"
    :input-type="inputType"
    :nick-name="renameValue"
    :name-focus="renameInputFocus"
    @confirm="confirmRename"
  />
  <!-- BIWD 启用时间 -->
  <Drawer v-model:show="activationTimeFlag" :title="$t('ApplianceSettings.ActivationTime.Dialog.Title')">
    <view class="activation-time-box">
      <view class="pickerBox">
        <picker-view
          mask-class="maskStyle"
          indicator-class="clearBorder"
          indicator-style="height: 45px;"
          class="picker-style"
          :value="curIndex"
          @change="changeElec"
        >
          <picker-view-column>
            <view
              class="pickerItem"
              :class="{ active: index === curIndex[0] }"
              v-for="(item, index) in nightModeStartTimeArray"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item.hour }}
            </view>
          </picker-view-column>
          <view class="spotUnitLeft"> : </view>
          <picker-view-column>
            <view
              class="pickerItem"
              :class="{ active: index === curIndex[1] }"
              v-for="(item, index) in nightModeStartTimeArray[curIndex[0]]?.minute || ['00']"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>
          <view class="picker-split-line"> - </view>
          <picker-view-column></picker-view-column>
          <picker-view-column>
            <view
              class="pickerItem"
              :class="{ active: index === curIndex[3] }"
              v-for="(item, index) in nightModeEndTimeArray"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item.hour }}
            </view>
          </picker-view-column>
          <view class="spotUnitRight"> : </view>
          <picker-view-column>
            <view
              class="pickerItem"
              :class="{ active: index === curIndex[4] }"
              v-for="(item, index) in nightModeEndTimeArray[curIndex[3]]?.minute || ['00']"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
        <view class="endUnit">{{ $t('ApplianceSettings.ActivationTime.Dialog.NextDay.Text') }}</view>
      </view>
    </view>
    <template #footer>
      <view class="activation-time-btn display-between">
        <view class="btn cancel--btn" @click="hideActivationTimePop">{{
          $t('ApplianceSettings.ActivationTime.Dialog.Cancel.Button')
        }}</view>
        <view class="btn save-btn" @click="saveActivationTime">{{
          $t('ApplianceSettings.ActivationTime.Dialog.Save.Button')
        }}</view>
      </view>
    </template>
  </Drawer>
  <!-- 设置日期和时间 -->
  <Drawer v-model:show="setDateTimeVisible" :title="$t('ApplianceSettings.ActivationTime.Dialog.Title')">
    <view class="activation-time-box">
      <view class="pickerBox">
        <picker-view
          mask-class="maskStyle"
          indicator-class="clearBorder"
          indicator-style="height: 45px;"
          class="picker-style"
          @change="changeDateTime"
          :value="setDateTimeIndex"
        >
          <picker-view-column style="flex: 2; text-align: right">
            <view
              class="pickerItem"
              :class="{ active: index === setDateTimeIndex[0] }"
              v-for="(item, index) in dateTimeList"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              <text>{{ item }}</text>
            </view>
          </picker-view-column>

          <picker-view-column style="flex: 1">
            <view
              class="pickerItem"
              :class="{ active: index === setDateTimeIndex[1] }"
              v-for="(item, index) in hourList"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>

          <view class="spotUnitRightTime"> : </view>

          <picker-view-column style="flex: 1">
            <view
              class="pickerItem"
              :class="{ active: index === setDateTimeIndex[2] }"
              v-for="(item, index) in minuteList"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    <template #footer>
      <view class="activation-time-btn display-between">
        <view class="btn cancel--btn" @click="hideSetDateTimePop">{{
          $t('ApplianceSettings.ActivationTime.Dialog.Cancel.Button')
        }}</view>
        <view class="btn save-btn" @click="saveDateTime">{{
          $t('ApplianceSettings.ActivationTime.Dialog.Save.Button')
        }}</view>
      </view>
    </template>
  </Drawer>
  <!-- 设置时间格式的设置项 -->
  <Drawer
    v-model:show="setTimeVisible"
    type="confirm"
    :title="timeUnitSetting?.name"
    :desc="timeUnitSetting?.mediumDescription"
    :confirm-text="$t('APP.Common.Define.Text')"
    @confirm="confirmTimeSetting"
  >
    <LimitedTimePicker
      v-if="timeUnitSetting !== null"
      v-model:value="setTimeSeconds"
      :min="timeUnitSetting.constraints?.min || 0"
      :max="timeUnitSetting.constraints?.max || 0"
      :stepsize="timeUnitSetting.constraints?.stepsize || 1"
      @change="changeTimePicker"
    />
  </Drawer>
  <!-- 运行模式弹框  -->
  <Modal
    :visible="runModeVisible"
    :title="$t('ApplianceSettings.RunMode.Dialog.Title')"
    :description="$t('ApplianceSettings.RunMode.Dialog.Content.Text')"
    :ok-text="$t('APP.Common.ISee.Text')"
    @ok="runModeVisible = false"
  />
  <!-- 水压状态提示框 -->
  <Modal
    :visible="showWaterPressureVisible"
    :title="$t('ApplianceSettings.WaterPressure.Dialog.Title')"
    :description="$t('ApplianceSettings.WaterPressure.Dialog.Content.Text')"
    :ok-text="$t('APP.Common.ISee.Text')"
    @ok="showWaterPressureVisible = false"
  />
  <!-- 气候补偿  -->
  <Modal
    :title="$t('ApplianceSettings.ClimateCompensation.Dialog.Title')"
    :description="$t('ApplianceSettings.ClimateCompensation.Dialog.Content.Text')"
    v-model:visible="showOpenLocation"
    :cancel-text="$t('ApplianceSettings.ClimateCompensation.Dialog.Cancel.Button')"
    :ok-text="$t('ApplianceSettings.ClimateCompensation.Dialog.Ok.Button')"
    @ok="confirmOpenLocation"
  />
  <!-- 设置机器当前时间 -->
  <Drawer v-model:show="setApplianceTimeVisible" :title="$t('ApplianceSettings.ApplianceTime.Dialog.Title')">
    <view class="activation-time-box">
      <view class="pickerBox pickerBoxApplianceTime">
        <picker-view
          mask-class="maskStyle"
          indicator-class="clearBorder"
          indicator-style="height: 45px;"
          class="picker-style"
          @change="changeApplianceTime"
          :value="setApplianceTimeIndex"
        >
          <picker-view-column style="flex: 1">
            <view
              class="pickerItem"
              :class="{ active: index === setApplianceTimeIndex[0] }"
              v-for="(item, index) in hourList"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>

          <view class="spotUnitRightApplianceTime"> : </view>

          <picker-view-column style="flex: 1">
            <view
              class="pickerItem"
              :class="{ active: index === setApplianceTimeIndex[1] }"
              v-for="(item, index) in minuteList"
              :key="index"
              style="line-height: 45px; height: 45px"
            >
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
    <template #footer>
      <view class="activation-time-btn display-between">
        <view class="btn cancel--btn" @click="hideSetApplianceTimePop">{{
          $t('ApplianceSettings.ApplianceTime.Dialog.Cancel.Button')
        }}</view>
        <view class="btn save-btn" @click="saveApplianceTime">{{
          $t('ApplianceSettings.ApplianceTime.Dialog.Save.Button')
        }}</view>
      </view>
    </template>
  </Drawer>
  <!-- EMS OTA升级弹框 -->
  <OtaUpgradeIRF :show="isMR100IRF || isMR100IRFEMS" :mcu-status="mcuStatus" />
  <!-- 固件升级成功 -->
  <SuccessAcknowledge v-if="otaHelper" :helper="otaHelper" />
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import SettingGroup from '@/common/setting/SettingGroup.vue'
import SettingRow from '@/common/setting/SettingRow.vue'
import Modal from '@/common/modal.vue'
import ErrorTips from '@/common/errorTips.vue'
import Drawer from '@/common/drawer.vue'
import RenameModal from '@/common/renameModal.vue'
import OtaUpgradeIRF from '@/pages/appliance/TT/otaUpgrade/otaUpgradeIRF.vue'
import { TrackType, trackEvent } from '@/dataReport/tracks'
import type {
  getApplianceDetail,
  getAllSetting,
  getFeatures,
  getGuest,
  deregister,
  changeApplianceName,
  setSetting,
  setHomeApplianceSettings,
  setHVNHomeApplianceSettings,
  getAppSupportCommands,
  getSimpleSetting,
  ApplianceSetting,
  ApplianceCommand,
  ApplianceDetail,
  getSettingGroups,
  ApplianceSimpleSetting,
  getStatus,
  ApplianceSettingDes,
  getSetting,
} from '@/api/appliance'
import type { getProfileVersion, getFirmwareVersion } from '@/api/biwd'
import { getOtaUpgradeList, type renameRoomName } from '@/api/tt'
import type { setUserAddition } from '@/api/account'
import { useApplianceStore } from '@/store/appliance'
import type { OTAHelper } from './ota/helpers/types'
import { useSmartDrying } from '../Dishwasher/smartDrying/useSmartDrying'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import {
  SETTING_APPLIANCEDATETIME,
  SETTING_SYNCHRONIZEWITHTIMESERVER,
  SETTING_REMOTE_CONTROL_LEVEL,
  HVN_SETTING_NIGHT_MODE,
  HVN_SETTING_NIGHT_MODE_TIME,
  HVN_SETTING_NIGHT_MODE_STARTHOUR,
  HVN_SETTING_NIGHT_MODE_STARTMIN,
  HVN_SETTING_NIGHT_MODE_ENDHOUR,
  HVN_SETTING_NIGHT_MODE_ENDMIN,
  TT_SUMMER_BLMODE,
  TT_SUMMER_MODE,
  TT_SETTING_ANTIFROZEN,
  TT_SETTING_WDC,
  MACHINE_TIME,
  REMOTE_CONTROL_START_ALLOWED,
  REMOTE_CONTROL_ACTIVE,
  TT_SETTING_WTPRESSURE,
  FU_VERSION,
  SETTING_TIMEZONE,
} from '@/constants/Command'
import {
  StandbyTime,
  NightModeState,
  NightModeBright,
  NightModeStartTime,
  NightModeEndTime,
  DatConfig,
  DatConfig_SetCollect,
  BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE,
  BIWD_WATERTREATMENT_CHILLEDWATERSET,
  BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
} from '@/constants/WDCommand'
import SmartDryingModal from '../Dishwasher/smartDrying/smartDryingModal.vue'
import { generateNightModeTimeList, prefixZero, sleepTimeListData } from '../BIWD/filterStatusList'
import { getSettingGroupData, type SettingGroupListType } from './settingsGroup'
import { useCommandsReset } from './commandsGroup'
import {
  showLoading,
  toPage,
  useRealTime,
  getDayIndex,
  getCurrentYearDateWeek,
  getPageQuery,
  toHome,
  actionDebounce,
  showModal,
} from '@/utils/mpHelper'
import netconfig from '@/config/netconfig'
import { useVirtualShareNotice } from '../Demo/utils'
import VirtualShareNotice from '../Demo/virtualShareNotice.vue'
import {
  getTTAntiFrozenMode,
  getTTSummerMode,
  getTTWDCMode,
  setTTWDCMode,
  TT_SETTING_BLANTIFROZEN,
  TT_SETTING_BlState,
  TT_SETTING_BlWtPressure,
  TT_SETTING_WDC_MR120,
  TT_STATUS_MCUSTATUS,
} from '../TT/SmartAssistantTool'
import { useTTErrorCode } from '../TT/TTHelper'
import { saveTTAddress, setTTSetting, type TTRoomDetailType } from '@/api/tt'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import type { WS } from '@/utils/socket/types'
import dayjs from 'dayjs'
import LimitedTimePicker, { type ChangePayload } from '../components/limitedTimePicker.vue'
import PrivacyPopup from '@/pages/navigator/components/privacyPopup.vue'
import { applianceControlTrack } from '@/dataReport/dataReportUtil'
import { isOemAppliance } from '../utils/ApplianceHelper'
import SuccessAcknowledge from './ota/modals/successAcknowledge.vue'
export type ApiControl = {
  getGuest: typeof getGuest
  getApplianceDetail: typeof getApplianceDetail
  changeApplianceName: typeof changeApplianceName
  getAppSupportCommands: typeof getAppSupportCommands
  getSimpleSetting: typeof getSimpleSetting
  getAllSetting: typeof getAllSetting
  getFeatures: typeof getFeatures
  setSetting: typeof setSetting
  setHomeApplianceSettings: typeof setHomeApplianceSettings
  setHVNHomeApplianceSettings: typeof setHVNHomeApplianceSettings
  deregister: typeof deregister
  setUserAddition: typeof setUserAddition
  renameRoomName: typeof renameRoomName
  getSettingGroups: typeof getSettingGroups
  getStatus: typeof getStatus
  getSetting: typeof getSetting
  getProfileVersion: typeof getProfileVersion
  getFirmwareVersion: typeof getFirmwareVersion
}

export type ToParameterSettingsPayload = {
  haId: string
  type: string
  vib: string
  title?: string
  key: string
  value?: string | number | boolean | null
  isVirtual?: boolean
  blState?: string | null
}

export type NightModeType = {
  hour: string
  minute: string[]
}

const props = defineProps<{
  apiControl: ApiControl
  otaHelper: OTAHelper | null
}>()
const emit = defineEmits<{
  (e: 'to-param-settings', payload: ToParameterSettingsPayload): void
}>()

type PageQueryOptions = {
  brand: string
  type: string
  vib: string
  haId: string
  name: string
  connected: 'true' | 'false'
  guest: 'true' | 'false'
  remoteControl: 'true' | 'false'
  remoteStart: 'true' | 'false'
  isVirtual?: 'true' | 'false'
  fromUsageReport?: 'true' | 'false'
}

const specialUserGuideTypes = ['HVN', 'TT']
const oemApplianceTypes = ['HVN', 'TT', 'BIWD']
const specialUserGuideLinks = [netconfig.HVN_USER_GUIDE_LINK]

const applianceStore = useApplianceStore()

const i18n = useI18n()
const pageStyle = {
  backgroundColor: '#f4f4f4',
}
const headerStyle = {
  backgroundColor: '#fff',
}
const switchColor = '#108ee9'
let settingId = ref('')
let settingButtonId = ref('')
const vib = ref('')
const haId = ref('')
const type = ref('')
const brand = ref('')
const name = ref('')
const isVirtual = ref(getPageQuery()?.isVirtual === 'true')
const detail = ref<ApplianceDetail | null>(null)
const appliance = computed(() => applianceStore.current)
const applianceImg = computed(() => `${netconfig.PHOTO_IMAGE}${vib.value}/${vib.value}.png`)
const guest = ref(false)
const connected = ref(false)
const remoteControl = ref(false)
const remoteStart = ref(false)
const consumablesServiceVisible = computed(() => ['FridgeFreezer', 'CoffeeMaker'].includes(type.value as string))

const showRemoveDialog = ref(false)
const removeText = ref('')

const renameModalVisible = ref(false)
const renameInputFocus = ref(false)
const renameValue = ref('')

const errorTipsFlag = ref(false)
const errorTipsText = ref('')

const settingList = ref<SettingGroupListType[]>([])
const supportCommands = ref<ApplianceCommand[]>([])

const RenameModalRef = ref<InstanceType<typeof RenameModal> | null>(null)

const sleepTime = ref('')
const sleepTimeValue = ref(0)
const sleepTimeVisible = ref(false)
const nightModeState = ref(false)
const nightModeStateVisible = ref(false)
const nightModeBright = ref(0)
const nightModeBrightVisible = ref(false)
const nightModeStartHour = ref('00')
const nightModeStartMinute = ref('00')
const nightModeEndHour = ref('00')
const nightModeEndMinute = ref('00')
const NightModeTimeVisible = ref(false)
const lockBIWDSet = ref(false)
const lockBIWDSetVisible = ref(false)
const coolWaterSet = ref(false)
const coolWaterSetVisible = ref(false)
const coolWaterTemp = ref(0)
const coolWaterTempVisible = ref(false)
const hvnNightModeState = ref(false)

const activationTime = computed(
  () =>
    nightModeStartHour.value +
    ':' +
    nightModeStartMinute.value +
    ' - 次日' +
    nightModeEndHour.value +
    ':' +
    nightModeEndMinute.value
)
const activationTimeFlag = ref(false)
const curIndex = ref([0, 0, 0, 0, 0])

const tempTime = ref(0)
const tempAutoTime = ref(new Date().getTime())
const autoTimeFlag = ref(false) //是否自动获取时间
const setDateTimeIndex = ref([0, 0, 0]) //设置日期和时间下标

const tempAllianceTime = ref(0)
const setApplianceTimeVisible = ref(false)
const setApplianceTimeIndex = ref([0, 0]) //设置机器的时间

const { autoTime, applianceTime, clearTimer } = useRealTime(tempAutoTime, tempAllianceTime)

const isMR120 = computed(() => haId.value.indexOf('MR120') !== -1)
const isMR100IRF = computed(() => haId.value.split('-')[1] === 'MR100iRF10720')
const isMR100IRFEMS = computed(() => haId.value.split('-')[1] === 'MR100iRF10720EMS')

const summerMode = ref(false) // 运行模式
const summerModeKey = ref('')
const runModeVisible = ref(false)
const blState = ref('')
const TTsettings = ref<TTRoomDetailType[]>([])
const { roomList, boilerErr } = useTTErrorCode(TTsettings, { isMR120, isMR100IRFEMS })
const mcuStatus = ref(0)

const renameTitle = ref('家电名称')
const inputType = ref('appliance')
const roomIndex = ref(0)
const FU_ver = ref<{ name: string | undefined; value: number | undefined }>({ name: '', value: 0 })
const { commandsGroups, resetCommand } = useCommandsReset(supportCommands, {
  guest,
  isVirtual,
})
const isBIWDVlueVib = computed(() =>
  ['WS5054BB1C', 'WS5053BB1C', 'WS5053BC1C', 'WS5054BC1C', 'WBB6050B1C', 'WBB6050C1C'].includes(vib.value)
)
const isShowBiwdValueOta = computed(() => netconfig.isTester && !isVirtual.value && isBIWDVlueVib.value)
const isHaveTimeZone = ref(false)

function onLoadCallback() {
  const query = getPageQuery<PageQueryOptions>()
  vib.value = query.vib
  haId.value = query.haId
  type.value = query.type
  brand.value = query.brand
  name.value = decodeURIComponent(query.name)
  isVirtual.value = query.isVirtual === 'true'
  guest.value = query.guest === 'true'
  connected.value = query.connected === 'true'
  remoteControl.value = query.remoteControl === 'true'
  remoteStart.value = query.remoteStart === 'true'

  if (type.value == 'TT') {
    let link = netconfig.TT_USER_GUIDE[vib.value]
    specialUserGuideLinks.push(link)
  }

  if (query.fromUsageReport === 'true') {
    props.apiControl.getStatus(query.haId).then((res) => {
      let status = res.data.status || []
      status.forEach((item) => {
        if (item.key === REMOTE_CONTROL_ACTIVE) {
          remoteControl.value = item.value as boolean
        } else if (item.key === REMOTE_CONTROL_START_ALLOWED) {
          remoteStart.value = item.value as boolean
        }
      })
    })
  }

  if (!isVirtual) {
    WebsocketManager.instance.connectWebsocket()
    if (isOemAppliance(type.value)) {
      WebsocketManager.instance.oemWebsocket?.addMessageListener(listenMessageCB)
    } else {
      WebsocketManager.instance.inhouseWebsocket?.addMessageListener(listenMessageCB)
    }
  }
  // ota升级
  if (connected.value && props.otaHelper) {
    if (type.value === 'BIWD' && !isBIWDVlueVib.value) return
    props.otaHelper.checkUpgrade()
  }
}
function onShowCallback() {
  const options = getPageQuery()

  nextTick(async () => {
    loadApplianceDetail()

    if (options.connected !== 'true') {
      if (!['HVN', 'TT'].includes(options.type)) {
        loadFeatures(haId.value)
      }

      return
    }

    if (options.type === 'BIWD') {
      upgradeBiwdNumber.value = 0
      loadSimpleSettings(haId.value)
      if (isShowBiwdValueOta.value) {
        getProfileVersionFun()
        getFirmwareVersionFun()
      }
    } else if (options.type === 'HVN') {
      loadHVNSettings(haId.value)
    } else if (options.type === 'TT') {
      loadTTSettings(haId.value)
      if (isMR120.value) judgeAllOtaVersion()
    } else {
      loadSettings(haId.value)
      loadSupportedCommands(haId.value)
    }
  })
}
function onUnloadCallback() {
  clearTimer()
  if (!isVirtual) {
    if (isOemAppliance(type.value)) {
      WebsocketManager.instance.oemWebsocket?.removeMessageListener(listenMessageCB)
    } else {
      WebsocketManager.instance.inhouseWebsocket?.removeMessageListener(listenMessageCB)
    }
  }
}
onShow(() => onShowCallback())
onUnload(() => onUnloadCallback())

onLoadCallback()
onShowCallback()

/**
 * 检查在线离线状态
 */
function checkOnline(): boolean {
  if (!connected.value) {
    showModal({
      content: i18n.t('Appliance.Settings.OfflineClickTips.Content'),
      confirmText: i18n.t('APP.Common.ISee.Text'),
      confirmColor: '#408DF2',
      showCancel: false,
    })
  }
  return connected.value
}

function getSettingId(setting: ApplianceSetting) {
  if (!connected.value) return
  settingId.value = setting.key
}
/**
 * 获取家电详情
 */
async function loadApplianceDetail() {
  const res = await props.apiControl.getApplianceDetail(haId.value)

  detail.value = res.data
}

/**
 * 洗碗机智能烘干
 */
const smartDrying = useSmartDrying()

/**
 * 获取家电settings列表
 * @param haId
 */
async function loadSettings(haId: string) {
  const res = await props.apiControl.getAllSetting(haId)
  const settings = res?.data?.settings || []
  loadSettingList(settings)
}

async function loadSettingList(settings: ApplianceSetting[]) {
  const settingsRes = await props.apiControl.getSettingGroups(type.value)
  let newSettings: SettingGroupListType[] = getSettingGroupData(settings, settingsRes?.data || [])
  settings.forEach((item) => {
    // features接口返回的不带value的数据 不做处理
    if (item.value === void 0) return

    if (typeof item.value === 'boolean') {
      item.checked = item.value
      if (item.key === SETTING_SYNCHRONIZEWITHTIMESERVER) {
        autoTimeFlag.value = item.value as unknown as boolean
        if (!autoTimeFlag.value) tempAutoTime.value = tempTime.value
      }
    } else if (item.key === SETTING_APPLIANCEDATETIME) {
      isHaveTimeZone.value = true
      let value = item.value as string
      let time = value.split('T')[0] + ' ' + value.split('T')[1]
      tempTime.value = new Date(time).getTime()
    } else if (item.key === MACHINE_TIME) {
      isHaveTimeZone.value = false
      let date = new Date()
      let newValue = (date.getFullYear() +
        '/' +
        (date.getMonth() + 1) +
        '/' +
        date.getDate() +
        ' ' +
        item.value) as string
      tempAllianceTime.value = new Date(newValue).getTime()
    }
  })
  settingList.value = newSettings
  if (type.value === 'RefrigeratorB') {
    const settings = settingList.value[0].settings
    const items = settings.find((items) => items.key === FU_VERSION)
    FU_ver.value.name = items?.name
    FU_ver.value.value = items?.value as number
    console.error(items)

    // let items = settingList.value.find((items) => items.key === FU_VERSION)
  }
}

/**
 * 获取家电features缓存
 */
async function loadFeatures(haId: string) {
  if (isVirtual.value) return

  const res = await props.apiControl.getFeatures(haId)
  const settings = res?.data?.settings || []
  if (type.value === 'BIWD') {
    loadSimpleSettingsList(settings as ApplianceSimpleSetting[])
  } else {
    loadSettingList(settings)
  }
}

/**
 * 获取家电commands 列表
 */
async function loadSupportedCommands(haId: string) {
  try {
    const res = await props.apiControl.getAppSupportCommands(haId)
    supportCommands.value = res.data.commands || []
  } catch (error) {
    console.error('获取commands失败', error)
  }
}

/**
 * 加载settings接口
 * @param settings
 */
async function loadSimpleSettings(haId: string) {
  try {
    const res = await props.apiControl.getSimpleSetting(haId)
    let settings = res.data.settings || []
    loadSimpleSettingsList(settings)
  } catch (error) {
    console.error('获取简易settings失败', error)
  }
}
/**
 * 过滤setting中的数据
 * @param settings
 */
function loadSimpleSettingsList(settings: ApplianceSimpleSetting[]) {
  if (!settings || settings.length === 0) return
  settings.forEach((item) => {
    if (item.key === StandbyTime) {
      sleepTimeVisible.value = true
      if (item.value !== void 0) {
        let curValue = [0, 1, 2, 3].includes(Number(item.value)) ? Number(item.value) : 0
        sleepTime.value = sleepTimeListData[curValue].value
        sleepTimeValue.value = item.value
      }
    } else if (item.key === NightModeState) {
      nightModeStateVisible.value = true
      if (item.value !== void 0) {
        nightModeState.value = !(Number(item.value) === 0)
      }
    } else if (item.key === NightModeBright) {
      nightModeBrightVisible.value = true
      if (item.value !== void 0) {
        nightModeBright.value = Number(item.value) + 1
      }
    } else if (item.key === NightModeStartTime) {
      NightModeTimeVisible.value = true
      if (item.value !== void 0) {
        nightModeStartHour.value = prefixZero(item.value as unknown as string, 4)?.substring(0, 2) || '00'
        nightModeStartMinute.value = prefixZero(item.value as unknown as string, 4)?.substring(2, 4) || '00'
      }
    } else if (item.key === NightModeEndTime) {
      NightModeTimeVisible.value = true
      if (item.value !== void 0) {
        nightModeEndHour.value = prefixZero(item.value as unknown as string, 4)?.substring(0, 2) || '00'
        nightModeEndMinute.value = prefixZero(item.value as unknown as string, 4)?.substring(2, 4) || '00'
      }
    } else if (item.key === BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE) {
      lockBIWDSetVisible.value = true
      if (item.value !== void 0) {
        lockBIWDSet.value = Number(item.value) === 1
      }
    } else if (item.key === BIWD_WATERTREATMENT_CHILLEDWATERSET) {
      coolWaterSetVisible.value = true
      if (item.value !== void 0) {
        coolWaterSet.value = Number(item.value) === 1
      }
    } else if (item.key === BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE) {
      coolWaterTempVisible.value = true
      if (item.value !== void 0) {
        coolWaterTemp.value = Number(item.value)
      }
    }
  })
}
/**
 * 获取TT settings
 * @param haId
 */
const frozenStatus = ref(false)
const waterPressure = ref(0)
const algorithmSwitch = ref(false)
const showOpenLocation = ref(false)

async function loadTTSettings(haId: string) {
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })
  try {
    const res = await props.apiControl.getAllSetting(haId)
    let { settings } = res.data
    TTsettings.value = settings as TTRoomDetailType[]
    settings.forEach((item) => {
      if ([TT_SUMMER_MODE, TT_SUMMER_BLMODE].includes(item.key)) {
        summerModeKey.value = item.key
        summerMode.value = !(Number(item.value) === 0)
      } else if ([TT_SETTING_ANTIFROZEN, TT_SETTING_BLANTIFROZEN].includes(item.key)) {
        frozenStatus.value = !(Number(item.value) === 0)
      } else if ([TT_SETTING_WTPRESSURE, TT_SETTING_BlWtPressure].includes(item.key)) {
        waterPressure.value = Number(item.value) / 100
      } else if ([TT_SETTING_WDC, TT_SETTING_WDC_MR120].includes(item.key)) {
        algorithmSwitch.value = !(Number(item.value) === 0)
      } else if ([TT_SETTING_BlState].includes(item.key)) {
        let newFrozenStatus = getTTAntiFrozenMode(item.value as string)
        let newSummerMode = getTTSummerMode(item.value as string)
        let newAlgorithmSwitch = getTTWDCMode(item.value as string)
        frozenStatus.value = !(newFrozenStatus === 0)
        summerMode.value = !(newSummerMode === 0)
        summerModeKey.value = item.key
        algorithmSwitch.value = !(newAlgorithmSwitch === 0)
        blState.value = item.value as string
      } else if ([TT_STATUS_MCUSTATUS].includes(item.key)) {
        mcuStatus.value = Number(item.value)
      }
    })
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
    console.error('获取TTsettings失败', error)
  }
}
/**
 * 获取HVN settings
 * @param haId
 */
async function loadHVNSettings(haId: string) {
  try {
    const res = await props.apiControl.getAllSetting(haId)
    let { settings } = res.data

    settings.forEach((item) => {
      if (item.key === HVN_SETTING_NIGHT_MODE_STARTHOUR) {
        nightModeStartHour.value =
          item.value!.toString().length > 1 ? item.value!.toString() : '0' + item.value!.toString()
      } else if (item.key === HVN_SETTING_NIGHT_MODE_STARTMIN) {
        nightModeStartMinute.value =
          item.value!.toString().length > 1 ? item.value!.toString() : '0' + item.value!.toString()
      } else if (item.key === HVN_SETTING_NIGHT_MODE_ENDHOUR) {
        nightModeEndHour.value =
          item.value!.toString().length > 1 ? item.value!.toString() : '0' + item.value!.toString()
      } else if (item.key === HVN_SETTING_NIGHT_MODE_ENDMIN) {
        nightModeEndMinute.value =
          item.value!.toString().length > 1 ? item.value!.toString() : '0' + item.value!.toString()
      } else if (item.key === HVN_SETTING_NIGHT_MODE) {
        // HVN 勿扰模式
        hvnNightModeState.value = item.value === 0 ? true : false
      }
    })
  } catch (error) {
    console.error('获取HVNsettings失败', error)
  }
}

/**
 * 跳转使用指南页面
 */
function gotoUseGuide() {
  // TT HVN使用报告特殊处理
  let temp_index = specialUserGuideTypes.indexOf(type.value)
  if (temp_index >= 0) {
    let url = specialUserGuideLinks[temp_index]
    openPdf(url)
  } else {
    let type = detail.value?.zh
    if (isVirtual) {
      if (!detail.value?.zh) {
        type = '嵌饮机'
      }
    }
    settingId.value = 'GuideVideo.Navigate.Title.Text'
    toPage('/pages/my/useGuide/useGuide', {
      vib: vib.value,
      name: name.value,
      type,
    })
  }
}
/**
 * 跳转共享管理页面
 */
const virtualShareNotice = useVirtualShareNotice()
function gotoShare() {
  settingId.value = 'ShareManage.NavigateTitle.Text'
  if (isVirtual.value) {
    return virtualShareNotice.open()
  }

  toPage('/pages/my/shareManage/shareManage', {
    haId: haId.value,
    type: type.value,
    name: name.value,
    vib: vib.value,
  })
}
/**
 * 点击移除家电
 */
async function removeAppliance() {
  settingId.value = 'ApplianceSettings.Buttom.Button'
  showLoading(async () => {
    let text = i18n.t('Appliance.Settings.RemoveAppliance.Dialog.NoUser.Content.Text')
    const res = await props.apiControl.getGuest(haId.value)
    if (res.data.guests.length > 0) {
      text = i18n.t('Appliance.Settings.RemoveAppliance.Dialog.HaveUser.Content.Text')
    }
    removeText.value = text
    showRemoveDialog.value = true
  })
}
/**
 * 确定移除家电
 */
async function confirmRemove() {
  try {
    showLoading(async () => {
      let res: any = null
      try {
        res = await props.apiControl.deregister(haId.value)
      } catch (error) {
        res = error
      } finally {
        trackEvent(
          'remove_appliance',
          { successOrNot: res.code == 0, error_code: res.code, response_msg: res.msg },
          TrackType.ApplianceDetail,
          'ShareAppliance.RemoveBeforeTips.Dialog.Sure'
        )
      }
      deregisterSuc()
    }, i18n.t('APP.Common.Submitting.Text'))
  } catch (e) {
    console.error(e)
    showRemoveDialog.value = false
  }
}
/**
 * 删除成功
 */
async function deregisterSuc() {
  uni.hideLoading()
  showRemoveDialog.value = false
  uni.showToast({
    title: '提交成功',
    mask: true,
    duration: 1000,
  })
  if (type.value == 'Dishwasher') {
    await props.apiControl.setUserAddition({ waterHardness: '' })
  }

  setTimeout(() => {
    toHome({ isVirtual: isVirtual.value })
  }, 1000)
}
/**
 * 取消删除
 */
function cancelRemove() {
  showRemoveDialog.value = false
}
/**
 * 点击修改名称
 */
function showRenameModal(type: string, roomName?: string, index?: number) {
  if (type === 'appliance') {
    settingId.value = 'ApplianceSettings.ApplianceName.Lable'
    renameTitle.value = '家电名称'
    inputType.value = 'appliance'
    renameModalVisible.value = true
    renameInputFocus.value = true
    renameValue.value = name.value as string
  } else {
    settingId.value = 'ApplianceSettings.UpdateRoom.Text'
    renameTitle.value = '房间名称'
    inputType.value = 'room'
    renameModalVisible.value = true
    renameInputFocus.value = true
    roomIndex.value = Number(index)
    renameValue.value = roomName as string
  }
}

/**
 * 确定重命名
 * @param value
 */
const confirmRename = actionDebounce({
  call: async (name: string, inputType?: string) => {
    let checkNameResult = RenameModalRef.value?.checknickname(name)
    if (!checkNameResult) {
      return
    }
    if (inputType === 'room') {
      changeRoomNameFun(name)
    } else {
      changeApplianceNameFun(name)
      trackEvent('before_rename_appliance', {}, TrackType.ApplianceDetail, 'Appliance.Setting.Change.ApplianceName')
    }
  },
})

/**
 * 改变家电名称
 * @param newName
 */
async function changeApplianceNameFun(newName: string) {
  try {
    const res = await props.apiControl.changeApplianceName(haId.value, newName)
    if (res.code === 0) {
      name.value = newName
      if (!isVirtual.value) {
        applianceStore.updateCurrentName(newName)
      }
    } else if (res.code === 616) {
      errorTipsFlag.value = true
      errorTipsText.value = '该名称已存在，换个名字吧'
    }
    safeTrack(() => {
      trackEvent(
        'rename_appliance',
        { successOrNot: res.code == 0, error_code: res.code, response_msg: res.msg },
        TrackType.ApplianceDetail,
        'Appliance.Setting.Change.ApplianceName'
      )
    })
  } catch (error: any) {
    safeTrack(() => {
      trackEvent(
        'rename_appliance',
        { successOrNot: false, error_code: error.code, response_msg: error.msg },
        TrackType.ApplianceDetail,
        'Appliance.Setting.Change.ApplianceName'
      )
    })
  } finally {
    hideRenameModal()
  }
}

/**
 * TT - 改变房间名称
 * @param newName
 */
async function changeRoomNameFun(newName: string) {
  let params = {
    data: {
      haid: haId.value,
      code: (roomList.value || [])[roomIndex.value].key,
      name: newName,
    },
  }
  const res = await props.apiControl.renameRoomName(params)
  if (res.code === 0) {
    if (roomList.value) {
      roomList.value[roomIndex.value].name = newName
    }
  }
  hideRenameModal()
}
/**
 * 重置所有重命名相关变相
 */
function hideRenameModal() {
  renameModalVisible.value = false
  renameValue.value = ''
  renameInputFocus.value = false
}
/**
 * 跳转参数设置页面
 */
async function jumpParamsSetting(item: ApplianceSetting) {
  if (!checkOnline()) return
  getSettingId(item)
  if (item.key === SETTING_APPLIANCEDATETIME || (!remoteControl.value && item.key !== SETTING_REMOTE_CONTROL_LEVEL))
    return
  emit('to-param-settings', {
    haId: haId.value,
    type: type.value,
    vib: vib.value,
    title: item.name as string,
    key: item.key,
    isVirtual: isVirtual.value,
  })
}
function jumpStringSetting(settingName: string, key: string, index: number) {
  if (type.value === 'BIWD' && !checkOnline()) return
  settingId.value = key
  if (!remoteControl.value || (!nightModeState.value && key === NightModeBright)) return
  emit('to-param-settings', {
    haId: haId.value,
    type: type.value,
    vib: vib.value,
    title: settingName,
    key,
    value: index,
    isVirtual: isVirtual.value,
    blState: blState.value,
  })
}
/**
 * 统一处理开关按钮
 * @param chooseItem
 */
const changeChecked = actionDebounce({
  loadingText: i18n.t('APP.Common.Loading.Text'),
  call: async (groupIndex: number, settingIndex: number, setting: ApplianceSetting) => {
    if (!checkOnline()) return
    if (!remoteControl.value) return
    let key = settingList.value[groupIndex].settings[settingIndex].key
    let value = !settingList.value[groupIndex].settings[settingIndex].checked

    let res: any = null
    try {
      res = await props.apiControl.setSetting(haId.value, key, value)

      if (key === SETTING_SYNCHRONIZEWITHTIMESERVER && value) {
        if (isHaveTimeZone.value) {
          await props.apiControl.setSetting(haId.value, SETTING_TIMEZONE, {
            tz: 'CST-8',
            tzName: 'Asia/Shanghai',
          })
          if (value) tempAutoTime.value = new Date().getTime()
        } else {
          let date = new Date()
          let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
          let minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
          let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
          let paramTime = `${hour}:${minute}:${seconds}`
          await props.apiControl.setSetting(haId.value, MACHINE_TIME, paramTime)
          let newValue = (date.getFullYear() +
            '/' +
            (date.getMonth() + 1) +
            '/' +
            date.getDate() +
            ' ' +
            paramTime) as string
          if (value) tempAllianceTime.value = new Date(newValue).getTime()
        }
      }

      settingList.value[groupIndex].settings[settingIndex].checked = value
      autoTimeFlag.value = value
    } catch (error) {
      res = error
    } finally {
      safeTrack(() => {
        trackEvent(
          'appliance_setting',
          {
            setting_key: setting.key,
            setting_value: value,
            successOrNot: res.code == 0,
            error_code: res.code,
            response_msg: res.msg,
          },
          TrackType.ApplianceDetail,
          'Appliance.Parameter.Settings.Select'
        )
      })
    }
  },
})
/**
 * BIWD-设置夜间模式
 */
const changeNightModeState = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    if (type.value === 'BIWD' && !checkOnline()) return
    if (!remoteControl.value) {
      return
    }
    if (type.value === 'BIWD' && isVirtual.value) {
      return (nightModeState.value = !nightModeState.value)
    }
    let trackKey = ''
    let trackValue = ''
    if (type.value === 'HVN') {
      trackKey = HVN_SETTING_NIGHT_MODE
      if (hvnNightModeState.value) {
        let settings = [
          {
            key: HVN_SETTING_NIGHT_MODE,
            value: 1,
          },
        ]
        trackValue = '1'
        await props.apiControl.setHVNHomeApplianceSettings(haId.value, HVN_SETTING_NIGHT_MODE, settings)
        // hvnNightModeState.value = !hvnNightModeState.value
      } else {
        let settings = [
          {
            key: HVN_SETTING_NIGHT_MODE,
            value: 0,
          },
        ]
        trackValue = '0'
        await props.apiControl.setHVNHomeApplianceSettings(haId.value, HVN_SETTING_NIGHT_MODE, settings)
        // hvnNightModeState.value = !hvnNightModeState.value
      }
    } else {
      trackKey = NightModeState
      trackValue = nightModeState.value
        ? 'WaterTreatment.BIWD.Setting.NightModeState.Off'
        : 'WaterTreatment.BIWD.Setting.NightModeState.On'
      let settings = [
        {
          key: DatConfig,
          value: DatConfig_SetCollect,
        },
        {
          key: NightModeState,
          value: nightModeState.value
            ? 'WaterTreatment.BIWD.Setting.NightModeState.Off'
            : 'WaterTreatment.BIWD.Setting.NightModeState.On',
        },
      ]
      let res: any = null
      try {
        res = await props.apiControl.setHomeApplianceSettings(haId.value, settings)
      } catch (error) {
        res = error
      } finally {
        // nightModeState.value = !nightModeState.value
        safeTrack(() => {
          trackEvent(
            'appliance_setting',
            {
              setting_key: trackKey,
              setting_value: trackValue,
              successOrNot: res.code == 0,
              error_code: res.code,
              response_msg: res.msg,
            },
            TrackType.ApplianceDetail,
            'Appliance.Settings.Parameter.Setting'
          )
        })
      }
    }
  },
})
/**
 * BIWD-设置启用时间
 */
const nightModeStartTimeArray = ref<NightModeType[]>([])
const nightModeEndTimeArray = ref<NightModeType[]>([])
//显示启动时间弹框
async function changeActivationTime() {
  if (type.value === 'BIWD' && !checkOnline()) return
  if (type.value === 'HVN') {
    if (!hvnNightModeState.value) {
      return
    } else {
      getTimeData()
      activationTimeFlag.value = true
    }
  } else {
    if (!remoteControl.value || !nightModeState.value) return
    getTimeData()
    activationTimeFlag.value = true
  }
}
/**
 * 获取时间数据
 */
function getTimeData() {
  let newNightModeStartTimeArray = generateNightModeTimeList(true, 23, 60)
  let newCurIndex = [0, 0, 0, 0, 0]
  for (let i = 0; i < newNightModeStartTimeArray.length; i++) {
    for (let j = 0; j < newNightModeStartTimeArray[i].minute.length; j++) {
      if (
        newNightModeStartTimeArray[i].hour === nightModeStartHour.value &&
        newNightModeStartTimeArray[i].minute[j] === nightModeStartMinute.value
      ) {
        newCurIndex[0] = i
        newCurIndex[1] = j
      }
    }
  }
  let newNightModeEndTimeArray = generateNightModeTimeList(
    false,
    Number(newNightModeStartTimeArray[newCurIndex[0]].hour),
    Number(newNightModeStartTimeArray[newCurIndex[0]].minute[newCurIndex[1]])
  )
  for (let x = 0; x < newNightModeEndTimeArray.length; x++) {
    for (let y = 0; y < newNightModeEndTimeArray[x].minute.length; y++) {
      if (
        newNightModeEndTimeArray[x].hour === nightModeEndHour.value &&
        newNightModeEndTimeArray[x].minute[y] === nightModeEndMinute.value
      ) {
        newCurIndex[3] = x
        newCurIndex[4] = y
      }
    }
  }
  nightModeStartTimeArray.value = newNightModeStartTimeArray
  nightModeEndTimeArray.value = newNightModeEndTimeArray
  nextTick(() => (curIndex.value = newCurIndex))
}
//监听启用时间变化
function changeElec(e: WechatMiniprogram.PickerChange) {
  let tmpNightModeStartHour = nightModeStartTimeArray.value[e.detail.value[0] as number].hour
  let tmpNightModeStartMinute =
    nightModeStartTimeArray.value[e.detail.value[0] as number].minute[e.detail.value[1] as number]
  let newNightModeEndTimeArray = generateNightModeTimeList(
    false,
    Number(tmpNightModeStartHour),
    Number(tmpNightModeStartMinute)
  )
  nightModeEndTimeArray.value = newNightModeEndTimeArray
  curIndex.value = [...(e.detail.value as number[])]
}
//隐藏启用事件弹框
function hideActivationTimePop() {
  activationTimeFlag.value = false
}
//保存启用时间设置
const saveActivationTime = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    if (type.value === 'HVN') {
      saveHVNActivationTime()
      return
    }
    let tmpNightModeStartHour = nightModeStartTimeArray.value[curIndex.value[0]].hour
    let tmpNightModeStartMinute = nightModeStartTimeArray.value[curIndex.value[0]].minute[curIndex.value[1]]
    let tmpNightModeEndHour = nightModeEndTimeArray.value[curIndex.value[3]].hour
    let tmpNightModeEndMinute = nightModeEndTimeArray.value[curIndex.value[3]].minute[curIndex.value[4]]

    let startTime = parseInt(tmpNightModeStartHour + tmpNightModeStartMinute)
    let endTime = parseInt(tmpNightModeEndHour + tmpNightModeEndMinute)
    let settings = [
      {
        key: DatConfig,
        value: DatConfig_SetCollect,
      },
      {
        key: NightModeState,
        value: 'WaterTreatment.BIWD.Setting.NightModeState.On',
      },
      {
        key: NightModeStartTime,
        value: startTime,
      },
      {
        key: NightModeEndTime,
        value: endTime,
      },
    ]
    let res: any = null
    try {
      res = await props.apiControl.setHomeApplianceSettings(haId.value, settings)
    } catch (error) {
      res = error
    } finally {
      hideActivationTimePop()
      nightModeStartHour.value = tmpNightModeStartHour
      nightModeStartMinute.value = tmpNightModeStartMinute
      nightModeEndHour.value = tmpNightModeEndHour
      nightModeEndMinute.value = tmpNightModeEndMinute
      safeTrack(() => {
        const TrackObj = {
          setting_key: 'switch_dark_mode',
          setting_value: `${activationTimeFlag.value == false ? '关' : '开'}、${nightModeStartHour.value}:${
            nightModeStartMinute.value
          }、次日${nightModeEndHour.value}:${nightModeEndMinute.value}`,
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        }
        trackEvent('appliance_setting', TrackObj, TrackType.ApplianceDetail, 'Appliance.Parameter.Settings.Select')
      })
    }
  },
})

/**
 * HVN保存时间
 */
async function saveHVNActivationTime() {
  let tmpNightModeStartHour = nightModeStartTimeArray.value[curIndex.value[0]].hour
  let tmpNightModeStartMinute = nightModeStartTimeArray.value[curIndex.value[0]].minute[curIndex.value[1]]
  let tmpNightModeEndHour = nightModeEndTimeArray.value[curIndex.value[3]].hour
  let tmpNightModeEndMinute = nightModeEndTimeArray.value[curIndex.value[3]].minute[curIndex.value[4]]

  let settings = [
    {
      key: HVN_SETTING_NIGHT_MODE,
      value: 0,
    },
    {
      key: HVN_SETTING_NIGHT_MODE_TIME,
      value: 0,
    },
    {
      key: HVN_SETTING_NIGHT_MODE_STARTHOUR,
      value: tmpNightModeStartHour,
    },
    {
      key: HVN_SETTING_NIGHT_MODE_STARTMIN,
      value: tmpNightModeStartMinute,
    },
    {
      key: HVN_SETTING_NIGHT_MODE_ENDHOUR,
      value: tmpNightModeEndHour,
    },
    {
      key: HVN_SETTING_NIGHT_MODE_ENDMIN,
      value: tmpNightModeEndMinute,
    },
  ]

  let valueString = ''
  settings.forEach((element, index) => {
    valueString = valueString + JSON.stringify(element)
  })

  let res: any = null
  try {
    res = await props.apiControl.setHVNHomeApplianceSettings(haId.value, HVN_SETTING_NIGHT_MODE, settings)
  } catch (error) {
    res = error
  } finally {
    safeTrack(() => {
      const TrackObj = {
        setting_key: HVN_SETTING_NIGHT_MODE,
        setting_value: valueString,
        successOrNot: res.code == 0,
        error_code: res.code,
        response_msg: res.msg,
      }

      trackEvent('appliance_setting', TrackObj, TrackType.ApplianceDetail, 'Appliance.Parameter.Settings.Select')
    })
  }
  hideActivationTimePop()
  nightModeStartHour.value = tmpNightModeStartHour
  nightModeStartMinute.value = tmpNightModeStartMinute
  nightModeEndHour.value = tmpNightModeEndHour
  nightModeEndMinute.value = tmpNightModeEndMinute
}
/**
 * 跳转耗材服务
 */
function jumpConsumablesService() {
  settingId.value = 'Appliance.ConsumablesService.Button.Text'
  toPage(`/pages/consumablesService/consumablesService?vib=${vib.value}`)
}
/**
 * 参数设置-设置时间和日期
 */
const setDateTimeVisible = ref(false) //是否显示设置日期和时间弹框
let hourList: string[] = []
let minuteList: string[] = []
let dateTimeList: string[] = getCurrentYearDateWeek()
for (let i = 0; i < 24; i++) {
  hourList.push(String(i).padStart(2, '0'))
}
for (let j = 0; j < 60; j++) {
  minuteList.push(String(j).padStart(2, '0'))
}
function openSetDateTime(setting: ApplianceSetting) {
  if (!checkOnline()) return
  if (autoTimeFlag.value || !remoteControl.value) return
  getSettingId(setting)
  let [curDate, time] = autoTime.value.split(' ')
  let curHour = time.substring(0, 2)
  let curMinute = time.substring(3, 5)
  let dateIndex = getDayIndex(curDate) - 1
  setDateTimeIndex.value = [dateIndex, Number(curHour), Number(curMinute)]
  setDateTimeVisible.value = true
}
//监听设置时间和日期的变化
function changeDateTime(e: WechatMiniprogram.PickerChange) {
  setDateTimeIndex.value = [...(e.detail.value as number[])]
}
//隐藏设置日期和时间弹框
function hideSetDateTimePop() {
  setDateTimeVisible.value = false
}
// 保存设置的时间
const saveDateTime = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    let dateTime = dateTimeList[setDateTimeIndex.value[0]]
    let curYear = new Date().getFullYear()
    let month = ''
    let tempDay = ''
    if (dateTime === '今天') {
      month = new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : '' + (new Date().getMonth() + 1)
      tempDay = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate() + ''
    } else {
      month =
        Number(dateTime.split('月')[0]) < 10
          ? '0' + Number(dateTime.split('月')[0])
          : Number(dateTime.split('月')[0]) + ''
      tempDay = dateTime.split('月')[1].split('日')[0] + ''
    }

    let day = Number(tempDay) < 10 ? '0' + tempDay : tempDay
    let hour = hourList[setDateTimeIndex.value[1]]
    let minute = minuteList[setDateTimeIndex.value[2]]
    let second = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
    let value = `${curYear}-${month}-${day}T${hour}:${minute}:${second}`

    let res: any = null
    try {
      res = await props.apiControl.setSetting(haId.value, SETTING_APPLIANCEDATETIME, value)
    } catch (error) {
      res = error
    } finally {
      safeTrack(() => {
        trackEvent(
          'appliance_setting',
          {
            setting_key: SETTING_APPLIANCEDATETIME,
            setting_value: value,
            successOrNot: res.code == 0,
            error_code: res.code,
            response_msg: res.msg,
          },
          TrackType.ApplianceDetail,
          'Appliance.Parameter.Settings.Select'
        )
      })
    }

    tempAutoTime.value = new Date(`${curYear}/${month}/${day} ${hour}:${minute}:${second}`).getTime()
    setDateTimeVisible.value = false
  },
})

/**
 * 设置时间类型
 */
const setTimeVisible = ref(false)
// 是否需要显示为TimePicker
function shouldUseTimePicker(setting: ApplianceSetting) {
  return setting.unit === 'seconds'
}
function getTimeDisplayValue(setting: ApplianceSetting) {
  const seconds = Number(setting.value) || 0
  const displayValue = dayjs().hour(0).minute(0).second(seconds).format('HH:mm:ss')
  return displayValue
}

// 弹框内数据
const timeUnitSetting = ref<ApplianceSettingDes | null>(null)
async function loadTimeSetting(setting: ApplianceSetting) {
  const { data } = await props.apiControl.getSetting(haId.value, setting.key)
  timeUnitSetting.value = data
}
const openTimePicker = actionDebounce({
  async call(setting: ApplianceSetting) {
    if (!checkOnline()) return
    timeUnitSetting.value = null
    await loadTimeSetting(setting)
    setTimeSeconds.value = (setting.value || 0) as number
    nextTick(() => {
      setTimeVisible.value = true
    })
  },
})
function closeTimePicker() {
  setTimeVisible.value = false
}
// 设置时间值
const setTimeSeconds = ref<number>(0)
function changeTimePicker(e: ChangePayload) {
  setTimeSeconds.value = e.totalSeconds
}
const confirmTimeSetting = actionDebounce({
  async call() {
    if (timeUnitSetting.value) {
      let res: any = null
      try {
        res = await props.apiControl.setSetting(haId.value, timeUnitSetting.value.key, setTimeSeconds.value)
      } catch (error) {
        res = error
      } finally {
        safeTrack(() => {
          trackEvent(
            'appliance_setting',
            {
              setting_key: timeUnitSetting.value?.key,
              setting_value: setTimeSeconds.value,
              successOrNot: res.code == 0,
              error_code: res.code,
              response_msg: res.msg,
            },
            TrackType.ApplianceDetail,
            'Appliance.Parameter.Settings.Select'
          )
        })
      }
    }
  },
  finally() {
    closeTimePicker()
  },
})

/**
 * 设置机器当前时间
 * @param setting
 */
function openApplianceTime(setting: ApplianceSetting) {
  if (!checkOnline()) return
  if (!remoteControl.value) return
  getSettingId(setting)
  let curHour = applianceTime.value.substring(0, 2)
  let curMinute = applianceTime.value.substring(3, 5)
  setApplianceTimeIndex.value = [Number(curHour), Number(curMinute)]
  setApplianceTimeVisible.value = true
}
function changeApplianceTime(e: WechatMiniprogram.PickerChange) {
  setApplianceTimeIndex.value = [...(e.detail.value as number[])]
}
function hideSetApplianceTimePop() {
  setApplianceTimeVisible.value = false
}
const saveApplianceTime = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    let hour = hourList[setApplianceTimeIndex.value[0]]
    let minute = minuteList[setApplianceTimeIndex.value[1]]
    let second = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
    let value = `${hour}:${minute}:${second}`
    let res: any = null
    try {
      res = await props.apiControl.setSetting(haId.value, MACHINE_TIME, value)
    } catch (error) {
      res = error
    } finally {
      safeTrack(() => {
        trackEvent(
          'appliance_setting',
          {
            setting_key: MACHINE_TIME,
            setting_value: value,
            successOrNot: res.code == 0,
            error_code: res.code,
            response_msg: res.msg,
          },
          TrackType.ApplianceDetail,
          'Appliance.Settings.Parameter.Setting'
        )
      })
    }
    let date = new Date()
    let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    let newValue = date.getFullYear() + '/' + month + '/' + day + ' ' + `${hour}:${minute}:${second}`
    tempAllianceTime.value = new Date(newValue).getTime()
    setApplianceTimeVisible.value = false
  },
})

/**
 * 修改气候补偿算法
 */
function changeAlgorithm() {
  if (algorithmSwitch.value) {
    controlAlgorithm()
  } else {
    getLocationTT()
  }
}

/**
 * 跳转MR120固件升级
 */
const toOtaUpdate = actionDebounce({
  call: async () => {
    await toPage('/pages/appliance/settings/ota/firmwareUpdate', {
      haId: haId.value,
      type: type.value,
      brand: brand.value,
      vib: vib.value,
      mcuStatus: mcuStatus.value,
    })
  },
})
function listenMessageCB(msg: WS.Message) {
  if (msg.haId !== haId.value) return

  // 在线离线处理
  if (msg.type === 'CONNECTED') {
    connected.value = true
  } else if (msg.type === 'DISCONNECTED') {
    connected.value = false
  }

  if (!Array.isArray(msg.items)) return
  handleMessages(msg.items)
}
function handleMessages(messages: WS.MessageItem[]) {
  console.log('handleMessages', messages)
  for (const item of messages) {
    for (const observe of observes) {
      if (observe.key === item.key) {
        observe.handler(item)
      }
    }
    FF: for (const settingListItem of settingList.value) {
      for (const settingItem of settingListItem.settings) {
        if (settingItem.key == item.key) {
          settingItem.displayvalue = item.displayvalue
          settingItem.name = item.name
          settingItem.value = item.value as string | boolean | number
          settingItem.checked = item.value
          console.log('handleMessages', settingItem, settingList.value)
          break FF
        }
      }
    }
  }
}

/**
 * 固件升级埋点
 */
function FirmwareUpgrade() {
  settingId.value = 'Appliance.Settings.FirmwareUpgrade.Title'
  settingButtonId.value = 'Appliance.Settings.FirmwareUpgrade.Title'
}
async function toDemoUpgradePage() {
  await toPage('/pages/appliance/Demo/settings/ota/firmwareUpdate')
}
/**
 * 改变气候补偿算法
 */
function controlAlgorithm() {
  showLoading(async () => {
    let key: string = ''
    let value: string = ''

    let data = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: TT_SETTING_WDC,
          value: !algorithmSwitch.value ? 1 : 0,
        },
      ],
    }
    key = TT_SETTING_WDC
    value = !algorithmSwitch.value ? '1' : '0'

    if (isMR100IRF.value || isMR100IRFEMS.value) {
      let newBlState = setTTWDCMode(blState.value, !algorithmSwitch.value ? '1' : '0')
      data = {
        settings: [
          {
            key: TT_SETTING_BlState,
            value: newBlState,
          },
        ],
      }
      key = TT_SETTING_BlState
      value = newBlState.toString()
    } else if (isMR120.value) {
      data = {
        settings: [
          {
            key: TT_SETTING_WDC_MR120,
            value: !algorithmSwitch.value ? 1 : 0,
          },
        ],
      }
      key = TT_SETTING_WDC_MR120
      value = !algorithmSwitch.value ? '1' : '0'
    }
    await setSettingFun(data, 'Algorithm', key, value)
  })
}
/**
 * 下发设置指令
 * @param params
 */
async function setSettingFun(params: {}, type: string, key?: string, value?: string) {
  const res = await setTTSetting(haId.value, params)
  if (res.code === 0) {
    if (type === 'Algorithm') {
      showOpenLocation.value = false
      algorithmSwitch.value = !algorithmSwitch.value
    }
    uni.showToast({
      title: '设置成功',
      icon: 'none',
    })
    safeTrack(() => {
      trackEvent(
        'appliance_setting',
        { setting_key: key, setting_value: value },
        TrackType.ApplianceDetail,
        'Appliance.Parameter.Settings.Select'
      )
    })
  }
}
/**
 * 获取设备gps
 */
function getLocationTT() {
  uni.getLocation({
    success: async (res) => {
      saveTTAddress(haId.value, res.longitude, res.latitude)
      controlAlgorithm()
    },
    fail: (error) => {
      uni.hideLoading()
      showOpenLocation.value = true
    },
  })
}
/**
 * 开启位置授权
 */
function confirmOpenLocation() {
  showOpenLocation.value = false
  uni.openSetting({
    success: (res) => {
      if (res['scope.userLocation']) {
        controlAlgorithm()
      }
    },
    fail(res) {
      console.log(res)
    },
  })
}

const observes: { key: string; handler: (message: WS.MessageItem) => any }[] = [
  {
    key: REMOTE_CONTROL_START_ALLOWED,
    handler: (message) => {
      remoteStart.value = message.value as boolean
    },
  },
  {
    key: REMOTE_CONTROL_ACTIVE,
    handler: (message) => {
      remoteControl.value = message.value as boolean
    },
  },
  // HVN
  {
    key: HVN_SETTING_NIGHT_MODE_STARTHOUR,
    handler: (message) => {
      nightModeStartHour.value =
        message.value!.toString().length > 1 ? message.value!.toString() : '0' + message.value!.toString()
    },
  },
  {
    key: HVN_SETTING_NIGHT_MODE_STARTMIN,
    handler: (message) => {
      nightModeStartMinute.value =
        message.value!.toString().length > 1 ? message.value!.toString() : '0' + message.value!.toString()
    },
  },
  {
    key: HVN_SETTING_NIGHT_MODE_ENDHOUR,
    handler: (message) => {
      nightModeEndHour.value =
        message.value!.toString().length > 1 ? message.value!.toString() : '0' + message.value!.toString()
    },
  },
  {
    key: HVN_SETTING_NIGHT_MODE_ENDMIN,
    handler: (message) => {
      nightModeEndMinute.value =
        message.value!.toString().length > 1 ? message.value!.toString() : '0' + message.value!.toString()
    },
  },
  {
    key: HVN_SETTING_NIGHT_MODE,
    handler: (message) => {
      hvnNightModeState.value = Number(message.value) === 0
    },
  },
  // BIWD
  {
    key: NightModeBright,
    handler: (message) => {
      nightModeBright.value = Number(message.value) + 1
    },
  },
  {
    key: StandbyTime,
    handler: (message) => {
      sleepTime.value = sleepTimeListData[Number(message.value)].value
      sleepTimeValue.value = Number(message.value)
    },
  },
  {
    key: NightModeState,
    handler: (message) => {
      nightModeState.value = !(Number(message.value) === 0)
    },
  },
  {
    key: NightModeStartTime,
    handler: (message) => {
      nightModeStartHour.value = prefixZero(message.value as unknown as string, 4)?.substring(0, 2) || '00'
      nightModeStartMinute.value = prefixZero(message.value as unknown as string, 4)?.substring(2, 4) || '00'
    },
  },
  {
    key: NightModeEndTime,
    handler: (message) => {
      nightModeEndHour.value = prefixZero(message.value as unknown as string, 4)?.substring(0, 2) || '00'
      nightModeEndMinute.value = prefixZero(message.value as unknown as string, 4)?.substring(2, 4) || '00'
    },
  },
  {
    key: BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
    handler: (message) => {
      lockBIWDSet.value = Number(message.value) === 1
    },
  },
  {
    key: BIWD_WATERTREATMENT_CHILLEDWATERSET,
    handler: (message) => {
      coolWaterSet.value = Number(message.value) === 1
    },
  },
  {
    key: BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE,
    handler: (message) => {
      coolWaterTemp.value = Number(message.value)
    },
  },
  // TT
  {
    key: TT_SUMMER_MODE,
    handler: (message) => {
      summerMode.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SUMMER_BLMODE,
    handler: (message) => {
      summerMode.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SETTING_ANTIFROZEN,
    handler: (message) => {
      frozenStatus.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SETTING_BLANTIFROZEN,
    handler: (message) => {
      frozenStatus.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SETTING_WTPRESSURE,
    handler: (message) => {
      waterPressure.value = Number(message.value) / 100
    },
  },
  {
    key: TT_SETTING_BlWtPressure,
    handler: (message) => {
      waterPressure.value = Number(message.value) / 100
    },
  },
  {
    key: TT_SETTING_WDC,
    handler: (message) => {
      algorithmSwitch.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SETTING_WDC_MR120,
    handler: (message) => {
      algorithmSwitch.value = !(Number(message.value) === 0)
    },
  },
  {
    key: TT_SETTING_BlState,
    handler: (message) => {
      let newFrozenStatus = getTTAntiFrozenMode(message.value as string)
      let newSummerMode = getTTSummerMode(message.value as string)
      let newAlgorithmSwitch = getTTWDCMode(message.value as string)
      frozenStatus.value = !(newFrozenStatus === 0)
      summerMode.value = !(newSummerMode === 0)
      algorithmSwitch.value = !(newAlgorithmSwitch === 0)
      blState.value = message.value as string
    },
  },
  {
    key: TT_STATUS_MCUSTATUS,
    handler: (message) => {
      mcuStatus.value = Number(message.value)
    },
  },
]

/**
 * 显示夏季模式提醒弹框
 */
function showSummerModeTips() {
  runModeVisible.value
}

/**
 * 水压状态提示框
 */
const showWaterPressureVisible = ref(false)
function showWaterPressureTips() {
  trackEvent('ApplianceSettings.WaterPressure.Lable.Tip', {}, TrackType.ApplianceDetail)
  showWaterPressureVisible.value = true
}

/**
 * 打开pdf
 */
function openPdf(item: string) {
  safeTrack(() => {
    trackEvent(
      'before_check_article_actionhandler',
      {},
      TrackType.ApplianceDetail,
      'Appliance.UserRepotr.Artile.Select'
    )
  })
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })
  uni.downloadFile({
    url: item,
    success: function (res) {
      wx.hideLoading()
      const filePath = res.tempFilePath
      uni.openDocument({
        filePath,
      })
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          {
            successOrNot: true,
          },
          TrackType.ApplianceDetail,
          'Appliance.UserRepotr.Artile.Select'
        )
      })
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showToast({
        title: i18n.t('APP.Common.OpenFail.Text'),
        icon: 'error',
      })
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          {
            successOrNot: false,
            error_code: error.code,
            response_msg: error.msg,
          },
          TrackType.ApplianceDetail,
          'Appliance.UserRepotr.Artile.Select'
        )
      })
    },
  })
}

/**
 * BIWD - 冰水设置
 */
const changeCoolWaterSet = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    if (!checkOnline()) return
    let settings = [
      {
        key: BIWD_WATERTREATMENT_CHILLEDWATERSET,
        value: !coolWaterSet.value ? 'TRUE' : 'FALSE',
      },
      {
        key: BIWD_WATERTREATMENT_CHILLEDWATERTEMPERATURE,
        value: coolWaterTemp.value,
      },
    ]
    await props.apiControl.setHomeApplianceSettings(haId.value, settings)
  },
})

/**
 * BIWD - 童锁设置
 */
const changeLockBIWDSet = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    if (!checkOnline()) return
    let isNewSetType = !['WS7060BB1C', 'WS7061BB1C', 'WBB8060B1C'].includes(vib.value)
    let settings = []
    if (isNewSetType) {
      settings = [
        {
          key: BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
          value: lockBIWDSet.value ? 'FALSE' : 'TRUE',
        },
      ]
    } else {
      settings = [
        {
          key: DatConfig,
          value: DatConfig_SetCollect,
        },
        {
          key: BIWD_WATERTREATMENT_CHILDLOCKHIGHTEMPERATURE,
          value: lockBIWDSet.value ? 'FALSE' : 'TRUE',
        },
      ]
    }
    await props.apiControl.setHomeApplianceSettings(haId.value, settings)
  },
})

/*
 * 判断是否需要升级 / 获取升级版本号
 */
const currentVersionTT = ref('')
const latestVersionTT = ref('')
const isUpgradeMR120 = ref(false)
const upgradeNumber = ref(0)
const OTPid = '00000000000000000000000035ad0000'
const MCUPid = '00000000000000000000000034ad0000'
const WIFIPid = '000000000000000000000000daac0000'
let curVersionList = [
  {
    pid: MCUPid,
    name: 'MCU',
    version: '',
    serverversion: '',
  },
  {
    pid: OTPid,
    name: 'OT',
    version: '',
    serverversion: '',
  },
  {
    pid: WIFIPid,
    name: 'WIFI',
    version: '',
    serverversion: '',
  },
]
async function judgeAllOtaVersion() {
  const res = await getOtaUpgradeList(haId.value)
  if (res.code === 0 && res.data) {
    let versionList = res.data || []

    // 查询是否需要升级和排序
    let upgradeNum = 0
    versionList.forEach((item) => {
      if (item.upgrade) {
        upgradeNum++
      }
    })
    if (upgradeNum > 0) {
      isUpgradeMR120.value = true
    } else {
      isUpgradeMR120.value = false
    }
    upgradeNumber.value = upgradeNum

    // 升级版本号
    let newValue = ''
    let latestValue = ''
    curVersionList.forEach((newItem) => {
      versionList.forEach((item) => {
        if (item.pid === newItem.pid) {
          newItem.version = item.version
          newItem.serverversion = item.serverversion
        }
      })
    })
    curVersionList.forEach((item, index) => {
      if (index != 2) {
        newValue += `${item.name}:${item.version}/`
        latestValue += `${item.name}:${item.serverversion}/`
      } else {
        newValue += `${item.name}:${item.version}`
        latestValue += `${item.name}:${item.serverversion}`
      }
    })
    currentVersionTT.value = newValue
    latestVersionTT.value = latestValue
  }
}

/**
 * 跳转biwd value ota升级
 */
const jumpBiwdValueOta = actionDebounce({
  showLoading: false,
  call: async () => {
    if (!checkOnline()) return
    toPage(`/pages/appliance/settings/ota/biwdValueUpdate`, {
      haId: haId.value,
    })
  },
})

/**
 * BIWD - OTA升级
 */
const upgradeBiwdNumber = ref(0)
async function getProfileVersionFun() {
  const res = await props.apiControl.getProfileVersion(haId.value)
  if (!res.data) return
  if (!!res.data.serverprofileversion.version && res.data.profileversion !== res.data.serverprofileversion.version) {
    upgradeBiwdNumber.value++
  }
}
async function getFirmwareVersionFun() {
  const res = await props.apiControl.getFirmwareVersion(haId.value)
  let versionList = res.data
  if (!versionList || versionList.length === 0) return
  versionList.forEach((item) => {
    if (!!item.serverVersion.version && item.version !== item.serverVersion.version) upgradeBiwdNumber.value++
  })
}
</script>

<style scoped lang="less">
@import '@/styles/common.less';
@import '@/styles/switch.less';

.tips-icon {
  width: 32rpx;
  height: 32rpx;
  margin-left: -10rpx;
  margin-top: 4rpx;
}
.appliance-settings {
  position: relative;
}
.alt-icon {
  width: 16rpx;
  height: 44rpx;
}
// 家电信息
.appliance-info-label {
  position: relative;
  .appliance-image {
    display: block;
    width: 120rpx;
    height: 120rpx;
  }
  .share-icon {
    position: absolute;
    top: -8rpx;
    left: -8rpx;
    width: 86rpx;
    height: 32rpx;
    line-height: 32rpx;
    text-align: center;
    color: #ffffff;
    background-color: #56c496;
    font-weight: 600;
    font-size: 20rpx;
  }
}

/*绿色样式（true的样式）*/
:deep(.wx-switch-input) {
  position: absolute;
  top: 0;
  right: 0;
  .generalSwitch();
}

.bottom-actions {
  // margin-top: -8rpx;
}
.remove-appliance {
  flex: 1;
  width: 100%;
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  color: var(--primary-color);
  text-align: center;
}

.ota-badge {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  background-color: #eb3a3a;
  color: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
}

// 启用时间
.activation-time-box {
  .pickerBoxApplianceTime {
    padding: 0 160rpx !important;
  }
  .pickerBox {
    position: relative;
    height: 330rpx;
    padding: 0 60rpx;

    .active {
      font-weight: 500;
      font-size: 48rpx;
      color: var(--primary-color);
    }

    .picker-style {
      width: 100%;
      height: 330rpx;
      text-align: center;
      font-size: 40rpx;
      line-height: 90rpx;
      color: #000;
      position: relative;
    }

    .endUnit,
    .spotUnitLeft,
    .spotUnitRight,
    .picker-split-line,
    .spotUnitRightTime,
    .spotUnitRightApplianceTime {
      position: absolute;
      top: 126rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 60rpx;
      height: 60rpx;
      color: var(--primary-color);
    }

    .spotUnitLeft {
      left: 90rpx;
    }

    .spotUnitRight {
      right: 90rpx;
    }

    .picker-split-line {
      right: 268rpx;
    }

    .spotUnitRightTime {
      right: 116rpx;
      color: var(--primary-color);
    }

    .spotUnitRightApplianceTime {
      right: 150rpx;
      color: var(--primary-color);
    }

    .endUnit {
      right: 20rpx;
      font-size: 24rpx;
      font-weight: 400;
    }
  }
}
</style>
